package com.ruoyi.kjy.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.kjy.domain.Enterprise;
import com.ruoyi.kjy.service.IEnterpriseService;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.kjy.domain.ResidencyApplication;
import com.ruoyi.kjy.service.IResidencyApplicationService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;

/**
 * 入驻申请
 *
 * @author ruoyi
 * @date 2023-04-27
 */
@RestController
@RequestMapping("/application")
public class ResidencyApplicationController extends BaseController {
    @Autowired
    private IResidencyApplicationService residencyApplicationService;
    @Autowired
    private IEnterpriseService enterpriseService;

    /**
     * 查询申请列表
     */
    @GetMapping("/list")
    public AjaxResult list(Integer current, Integer size, ResidencyApplication residencyApplication) {
        if (Objects.isNull(current)) {
            current = 1;
        }
        if (Objects.isNull(size)) {
            size = 10;
        }
        if (size >= 20) {
            size = 20;
        }
        Page<ResidencyApplication> list = residencyApplicationService.page(new Page<>(current, size), new LambdaQueryWrapper<ResidencyApplication>().setEntity(residencyApplication));
        List<ResidencyApplication> records = list.getRecords();
        Stream<Long> longStream = records.stream().map(ResidencyApplication::getEnterpriseId);
        for (ResidencyApplication record : records) {
            Enterprise byId = enterpriseService.getById(record.getEnterpriseId());
            if (byId != null) {
                record.setBusinessLicense(byId.getBusinessLicense());
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 获取申请详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ResidencyApplication byId = residencyApplicationService.getById(id);
        Enterprise enterprise = enterpriseService.getById(byId.getEnterpriseId());
        if (byId != null&&enterprise!=null) {
            byId.setBusinessLicense(enterprise.getBusinessLicense());
        }
        return success(byId);
    }

    /**
     * 新增申请
     */
    @Log(title = "申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ResidencyApplication residencyApplication) {
//        Long enterpriseId = residencyApplication.getEnterpriseId();
        // 企业id应该从用户身上取，而不是入驻申请的id
        Long enterpriseId = SecurityUtils.getLoginUser().getSysUser().getEnterpriseId();
        Enterprise enterprise = enterpriseService.getById(enterpriseId);
        if (enterprise != null && enterprise.getState() == 1) {
            throw new ServiceException("企业已入驻");
        }
        //判断该企业是否已有申请
        ResidencyApplication residencyApplication1 = new ResidencyApplication();
        residencyApplication1.setEnterpriseId(residencyApplication.getEnterpriseId());
        List<ResidencyApplication> list = residencyApplicationService.list(new LambdaQueryWrapper<ResidencyApplication>().setEntity(residencyApplication1));
        if (list!=null && !list.isEmpty()){
            throw new ServiceException("该企业已有申请");
        }
        //判断该用户是否已有申请
        ResidencyApplication residencyApplication2 = new ResidencyApplication();
        residencyApplication2.setApplicantId(SecurityUtils.getUserId());
        List<ResidencyApplication> list1 = residencyApplicationService.list(new LambdaQueryWrapper<ResidencyApplication>().setEntity(residencyApplication2));
        if (list1!=null && !list1.isEmpty()){
            throw new ServiceException("该用户已有申请");
        }
        //插入
        residencyApplication.setState(0);
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        residencyApplication.setEnterpriseId(sysUser.getEnterpriseId());
        residencyApplication.setApplicantId(sysUser.getUserId());
        return toAjax(residencyApplicationService.save(residencyApplication));
    }
    /**
     * 管理端新增申请
     */
    @Log(title = "申请", businessType = BusinessType.INSERT)
    @PostMapping
    @RequestMapping("/adminAdd")
    public AjaxResult adminAdd(@RequestBody ResidencyApplication residencyApplication) {
        Long enterpriseId = residencyApplication.getEnterpriseId();
        Enterprise enterprise = enterpriseService.getById(enterpriseId);
        if (enterprise != null && enterprise.getState() == 1) {
            throw new ServiceException("企业已入驻");
        }
        //判断该企业是否已有申请
        ResidencyApplication residencyApplication1 = new ResidencyApplication();
        residencyApplication1.setEnterpriseId(residencyApplication.getEnterpriseId());
        List<ResidencyApplication> list = residencyApplicationService.list(new LambdaQueryWrapper<ResidencyApplication>().setEntity(residencyApplication1));
        if (list!=null && !list.isEmpty()){
            throw new ServiceException("该企业已有申请");
        }
        //插入
        residencyApplication.setState(1);
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        //residencyApplication.setEnterpriseId(sysUser.getEnterpriseId());
        residencyApplication.setApplicantId(sysUser.getUserId());
        return toAjax(residencyApplicationService.save(residencyApplication));
    }
    /**
     * 修改申请
     */
    @Log(title = "申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ResidencyApplication residencyApplication) {
        Integer state = residencyApplication.getState();
        ResidencyApplication byId1 = residencyApplicationService.getById(residencyApplication.getId());
        if (state == 1) {
            String username = SecurityUtils.getUsername();
            String createBy = residencyApplication.getCreateBy();
            Enterprise enterprise = enterpriseService.getById(byId1.getEnterpriseId());
//            如果是用户自己修改自己的入驻申请，则需要将状态置为审核中
            if (username.equals(createBy)) {
                residencyApplication.setState(0);
                enterprise.setState(0);
            } else {
//                如果是管理员修改状态，则不需要将审核状态置为审核中
                enterprise.setState(1);
            }
            enterpriseService.updateById(enterprise);
        }
        return toAjax(residencyApplicationService.updateById(residencyApplication));
    }

    /**
     * 删除申请
     */
    @Log(title = "申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(residencyApplicationService.removeByIds(Arrays.asList(ids)));
    }
}
